package com.group3.utils;

import com.group3.exception.BusinessException;
import com.group3.exception.ExceptionEnum;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * UploadUtil
 *
 * @author HY
 * 2021/05/14 11:32
 **/


public class UploadUtil {
    //源文件名
    private String originalFilename;

    //源文件后缀名
    private String suffix;

    //存入数据库里的tomcat虚拟路径
    private String dbPath;

    //文件大小
    private long size;

    //实际存储路径
    private String realPath;

     /***
      * 文件上传工具类
      * @Author HY
      * @Description
      * @Date  2021/06/18
      * @param: attach  文件流
      * @param: path    文件保存路径
      * @param: id      文件上传者id
      * @return
      **/
    public void doUpload(MultipartFile attach, String path, String id){

        if(!attach.isEmpty()){
            //获取上传文件的原文件名
            originalFilename = attach.getOriginalFilename();

            //不带后缀的文件名
            String name = originalFilename.substring(0,originalFilename.lastIndexOf("."));
            System.out.println("==>上传的文件名："+originalFilename);

            //获取文件名后缀（判断文件类型）
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println("==>上传的文件后缀名："+suffix);

            //获取文件大小
//            size = attach.getSize();
//            System.out.println("==>上传文件的大小："+size);

//            String currentFilename = System.currentTimeMillis()+ UUID.randomUUID().toString() + suffix;
            String currentFilename = name + id + System.currentTimeMillis() + suffix;
//            System.out.println("==>存储的上传文件名："+currentFilename);

            realPath = System.getProperty("user.dir") + "/src/main/resources/static/" +path ;
            System.out.println("==>上传文件保存的真实路径："+realPath);

            File targetFile = new File(realPath, currentFilename);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }

            try{
                attach.transferTo(targetFile);
            }catch (Exception e){
                //抛出文件上传失败异常
                throw new BusinessException(ExceptionEnum.UPLOAD_FILE_FAILED);
            }
//            realPath = realPath + "/" + currentFilename;
//            dbPath =  request.getContextPath() + "/" + uploader + "/" + "/" + currentFilename;
//            System.out.println(dbPath);
            //文件上传后的保存路径
            dbPath = "/" + path + "/" + currentFilename;
        }else{
            throw new BusinessException(ExceptionEnum.UPLOAD_FILE_FAILED);
        }
    }
    public String getUploadFile(){
        return dbPath;
    }

    public boolean delete(String path){

        try {
            java.io.File myDelFile = new java.io.File(path);
            myDelFile.delete();
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

